<template>
  <el-card style="width: 100%">
    <!-- 顶部标签页 -->
    <el-tabs v-model="activeTab" type="border-card">
      <!-- 基础信息表单 -->
      <el-tab-pane label="基础信息" name="basic">
        <div v-show="activeTab === 'basic'" class="p-6">
          <el-form
            ref="basicFormRef"
            :model="basicForm"
            :rules="basicRules"
            label-width="120px"
          >
            <el-form-item label="商品名称" prop="name" required>
              <el-input
                v-model="basicForm.name"
                placeholder="请填写商品名称,不超过200个字符内容"
                maxlength="200"
                show-word-limit
              />
            </el-form-item>

            <el-row :gutter="20">
              <!-- 左列 -->
              <el-col :span="12">
                <el-form-item label="商品分类" required>
                  <div class="category-select">
                    <el-tree-select
                      ref="treeSelectRef"
                      v-model="basicForm.cateId"
                      :data="categoryTree"
                      :props="defaultProps"
                      :render-after-expand="true"
                      :default-expand-all="true"
                      :show-checkbox="false"
                      :check-strictly="true"
                      :current-node-key="basicForm.cateId"
                      node-key="id"
                      placeholder="请选择商品分类"
                      class="!w-[360px]"
                      @change="handleCategoryChange"
                    >
                    </el-tree-select>
                  </div>
                </el-form-item>

                <el-form-item label="商品编码" required>
                  <div class="input-with-button">
                    <el-input
                      v-model="basicForm.spuNo"
                      placeholder="请输入商品编码"
                      class="!w-[260px]"
                      :readonly="!isNew"
                    />
                    <el-button
                      type="primary"
                      class="generate-btn"
                      @click="generateCode"
                      :disabled="!isNew"
                    >
                      <el-icon><RefreshRight /></el-icon>生成编码
                    </el-button>
                  </div>
                </el-form-item>

                <el-form-item label="销售价">
                  <el-input-number
                    v-model="basicForm.salePrice"
                    :min="0"
                    :precision="2"
                    placeholder="请输入销售价"
                    class="!w-[260px]"
                  />
                </el-form-item>
              </el-col>

              <!-- 右列 -->
              <el-col :span="12">
                <el-form-item label="商品品牌">
                  <el-select
                    v-model="basicForm.brandId"
                    placeholder="请选择品牌"
                    clearable
                    class="!w-[360px]"
                  >
                    <el-option
                      v-for="brand in brandOptions"
                      :key="brand.id"
                      :label="brand.name"
                      :value="brand.id"
                    />
                  </el-select>
                </el-form-item>

                <el-form-item label="划线价">
                  <el-input-number
                    v-model="basicForm.linePrice"
                    :min="0"
                    :precision="2"
                    placeholder="划线价"
                    class="!w-[260px]"
                  />
                </el-form-item>
              </el-col>
            </el-row>

            <el-form-item label="商品简介" required>
              <el-input
                v-model="basicForm.brief"
                type="textarea"
                :rows="4"
                placeholder="请填写商品简介"
                class="!w-[560px]"
              />
            </el-form-item>

            <div class="other-params mt-6">
              <div class="text-lg font-bold mb-4">其他参数</div>

              <el-row :gutter="20">
                <!-- 左列 -->
                <el-col :span="12">
                  <el-form-item label="单位" required>
                    <el-select
                      v-model="basicForm.unit"
                      placeholder="请选择单位"
                      filterable
                      allow-create
                      default-first-option
                      :reserve-keyword="false"
                      style="width: 240px"
                    >
                      <el-option
                        v-for="item in unitOptions"
                        :key="item"
                        :label="item"
                        :value="item"
                      />
                    </el-select>
                  </el-form-item>

                  <el-form-item label="是否上架">
                    <el-switch v-model="basicForm.isOnSale" />
                  </el-form-item>

                  <el-form-item label="是否推荐">
                    <el-switch v-model="basicForm.isRecommend" />
                  </el-form-item>
                </el-col>

                <!-- 右列 -->
                <el-col :span="12">
                  <el-form-item label="初始销量" required>
                    <el-input-number
                      v-model="basicForm.initialSales"
                      :min="1"
                      style="width: 80px"
                    />
                  </el-form-item>

                  <el-form-item label="虚拟商品">
                    <el-switch v-model="basicForm.isVirtual" />
                  </el-form-item>

                  <el-form-item label="是否热门">
                    <el-switch v-model="basicForm.isHot" />
                  </el-form-item>
                </el-col>
              </el-row>
            </div>
          </el-form>
        </div>
      </el-tab-pane>
      <el-tab-pane label="图集/视频" name="media">
        <!-- 图集/视频 -->
        <div v-show="activeTab === 'media'" class="p-6">
          <div class="mb-6">
            <el-alert :closable="false">
              <ol>
                <li>
                  图片支持jpg、gif、png、jpeg格式上传，建议尺寸：250*250。
                </li>
                <li>
                  【封面图】显示在列表页面供用户浏览的第一张图片，建议尺寸：250*250。
                </li>
                <li>【图集】显示商品详情页面动态滚动图，建议尺寸：800*800。</li>
                <li>【图集】建议数量制在10张以内</li>
              </ol>
            </el-alert>

            <div class="mb-6">
              <div class="font-bold mb-2">封面图：</div>
              <el-upload
                :headers="uploadHeaders"
                :action="uploadUrl"
                class="avatar-uploader"
                :show-file-list="false"
                :on-success="
                  (response) => handleUploadSuccess(response, 'cover')
                "
                :on-error="handleUploadError"
                :before-upload="beforeUpload"
              >
                <img
                  v-if="basicForm.primaryImage"
                  :src="basicForm.primaryImage"
                  class="avatar"
                />
                <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
              </el-upload>
            </div>

            <div class="mb-6">
              <div class="font-bold mb-2">图集：</div>
              <el-upload
                :headers="uploadHeaders"
                :action="uploadUrl"
                list-type="picture-card"
                :limit="10"
                :on-success="
                  (response) => handleUploadSuccess(response, 'gallery')
                "
                :on-error="handleUploadError"
                :before-upload="beforeUpload"
                :on-remove="handleRemove"
                :on-preview="handlePictureCardPreview"
                :file-list="
                  basicForm.images.map((url, index) => ({
                    url,
                    name: `商品图片${index + 1}`,
                    uid: index,
                  }))
                "
              >
                <el-icon><Plus /></el-icon>
              </el-upload>

              <!-- 添加图片预览对话框 -->
              <el-dialog v-model="dialogVisible" title="预览">
                <img
                  w-full
                  :src="dialogImageUrl"
                  alt="Preview Image"
                  style="max-width: 100%"
                />
              </el-dialog>
            </div>

            <div>
              <div class="font-bold mb-2">频：</div>
              <el-upload
                :headers="uploadHeaders"
                :action="uploadUrl"
                :limit="1"
                :on-success="
                  (response) => handleUploadSuccess(response, 'video')
                "
                :on-error="handleUploadError"
                accept="video/*"
              >
                <el-button type="primary">上传视频</el-button>
              </el-upload>
              <el-alert :closable="false">
                <ol>
                  <li>支持常用视频和视频格式，但是建议使用mp4格式</li>
                  <li>其他格式可能会有兼容性问题， 并且部分上传可能会很慢，</li>
                  <li>
                    如果有大文件上传，请对接技术人员上传视频，上传到第三方视频网站后复制链接
                  </li>
                </ol>
              </el-alert>
            </div>
          </div>
        </div>
      </el-tab-pane>
      <el-tab-pane label="规格设置" name="spec">
        <div v-show="activeTab === 'spec'" class="p-6">
          <el-alert :closable="false">
            <ol>
              <li>规格用于定义商品的销售属性，如颜色、尺码等</li>
              <li>添加规格后将自动生成对应的SKU组合</li>
              <li>建议规格数量不超过3个，规格值不超过10个</li>
            </ol>
          </el-alert>
          <!-- 添加规格按钮 -->
          <div class="mt-4" style="margin: 10px">
            <el-button type="primary" @click="addSpec">
              <el-icon><Plus /></el-icon>添加规格
            </el-button>
          </div>
          <!-- 规格树形结构 -->
          <el-tree
            :data="specTreeData"
            node-key="id"
            default-expand-all
            :expand-on-click-node="false"
            class="mt-4 spec-tree"
          >
            <template #default="{ node, data }">
              <span class="custom-tree-node">
                <!-- 规格名称/规格值显示 -->
                <span class="name-wrapper">
                  <el-input
                    v-if="data.isEditing"
                    v-model="data.inputValue"
                    size="small"
                    :placeholder="
                      data.type === 'spec' ? '请输入规格名称' : '请输入规格值'
                    "
                    @blur="handleInputBlur(data)"
                    @keyup.enter="handleInputBlur(data)"
                    class="!w-[180px]"
                  />
                  <span v-else class="name-text">{{ data.name }}</span>
                </span>

                <!-- 操作按钮 -->
                <span class="operation-buttons">
                  <template v-if="data.type === 'spec'">
                    <el-button type="primary" link @click="addSpecValue(data)">
                      添加值
                    </el-button>
                    <el-button
                      type="danger"
                      link
                      @click="removeNode(node, data)"
                    >
                      删除
                    </el-button>
                  </template>
                  <template v-else>
                    <el-button type="primary" link @click="editNode(data)">
                      编辑
                    </el-button>
                    <el-button
                      type="danger"
                      link
                      @click="removeNode(node, data)"
                    >
                      删除
                    </el-button>
                  </template>
                </span>
              </span>
            </template>
          </el-tree>
        </div>
      </el-tab-pane>
      <el-tab-pane label="SKU/库存" name="sku">
        <!-- SKU/库存设置 -->
        <div v-show="activeTab === 'sku'" class="p-6">
          <el-alert :closable="false">
            <ol>
              <li>
                前端商品详情显示的是最低价（显示的价格），只有选择对应的规才会显示下不同的规格价格
              </li>
              <li>
                【开启SKU】是指是否开启商品的SKU功能，如果，则可以选择商品的SKU，如果不开启，则商品只有一个商品。
              </li>
            </ol>
          </el-alert>

          <!-- 总库存和已售数统计 -->
          <div class="stock-summary">
            <el-row :gutter="20" class="mb-4">
              <el-col :span="12">
                <el-form-item label="总库存">
                  <el-input-number
                    v-model="basicForm.spuStockQuantity"
                    :min="0"
                    :disabled="skuForm.enabled"
                    class="!w-[120px]"
                    @change="handleTotalStockChange"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="已售数量">
                  <el-input-number
                    v-model="basicForm.soldQuantity"
                    :min="0"
                    :disabled="true"
                    class="!w-[120px]"
                  />
                </el-form-item>
              </el-col>
            </el-row>
          </div>

          <!-- 添加一个开关来控制是否启用SKU -->
          <!--div class="mb-4">
            <el-switch
              v-model="skuForm.enabled"
              :active-text="'启用多规格'"
              @change="handleSkuEnabledChange"
            />
          </div-->

          <!-- SKU表格 -->
          <el-table v-if="skuForm.enabled" :data="skuForm.list" border>
            <el-table-column type="selection" width="55" />
            <el-table-column label="图片" width="170">
              <template #default>
                <el-upload
                  :headers="uploadHeaders"
                  :action="uploadUrl"
                  list-type="picture-card"
                  :limit="1"
                  :on-success="
                    (response) => handleUploadSuccess(response, 'sku')
                  "
                  :on-error="handleUploadError"
                  :before-upload="beforeUpload"
                >
                  <el-icon><Plus /></el-icon>
                </el-upload>
              </template>
            </el-table-column>
            <el-table-column label="货号" prop="code" width="220">
              <template #default="{ row }">
                <el-input
                  v-model="row.code"
                  style="width: 190px"
                  :disabled="true"
                />
              </template>
            </el-table-column>
            <el-table-column label="规格属性" prop="specValues" width="220">
              <template #default="{ row }">
                <el-input
                  v-model="row.specValues"
                  style="width: 190px"
                  :disabled="true"
                />
              </template>
            </el-table-column>

            <el-table-column label="库存" width="150">
              <template #default="{ row }">
                <el-input-number
                  v-model="row.stock"
                  :min="0"
                  style="width: 125px"
                  @change="(val) => handleSkuStockChange(val, row)"
                />
              </template>
            </el-table-column>
            <el-table-column label="销售价" width="155">
              <template #default="{ row }">
                <el-input-number
                  v-model="row.salePrice"
                  :min="0"
                  :precision="2"
                  style="width: 130px"
                />
              </template>
            </el-table-column>
            <el-table-column label="划线价" width="155">
              <template #default="{ row }">
                <el-input-number
                  v-model="row.linePrice"
                  :min="0"
                  :precision="2"
                  style="width: 130px"
                />
              </template>
            </el-table-column>
            <el-table-column label="成本价" width="155">
              <template #default="{ row }">
                <el-input-number
                  v-model="row.costPrice"
                  :min="0"
                  :precision="2"
                  style="width: 130px"
                />
              </template>
            </el-table-column>
            <el-table-column label="市场价" width="155">
              <template #default="{ row }">
                <el-input-number
                  v-model="row.marketPrice"
                  :min="0"
                  :precision="2"
                  style="width: 130px"
                />
              </template>
            </el-table-column>
            <el-table-column label="重量(克)" width="150">
              <template #default="{ row }">
                <el-input-number
                  v-model="row.weight"
                  :min="0"
                  style="width: 125px"
                />
              </template>
            </el-table-column>
            <el-table-column label="积分" width="150">
              <template #default="{ row }">
                <el-input-number
                  v-model="row.points"
                  :min="0"
                  style="width: 125px"
                />
              </template>
            </el-table-column>
            <el-table-column label="操作" width="100">
              <template #default>
                <el-button type="danger" size="small">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-tab-pane>
      <el-tab-pane label="商品详情" name="details">
        <!-- 商品详情 -->
        <div v-show="activeTab === 'details'" class="p-6">
          <el-alert :closable="false">
            <ol>
              <li>
                图片支持直接在编辑中粘贴上传，然后在当前编辑器中粘贴即上传。
              </li>
              <li>
                微信小程序仅支持图片，不支持文字、不支持视频，请使用H5链接。
              </li>
            </ol>
          </el-alert>
          <div class="border">
            <Toolbar
              style="border-bottom: 1px solid #ccc"
              :editor="editorRef"
              :defaultConfig="toolbarConfig"
              mode="default"
            />
            <Editor
              style="height: 500px"
              v-model="editorContent"
              :defaultConfig="editorConfig"
              mode="default"
              @onCreated="handleCreated"
            />
          </div>
        </div>
      </el-tab-pane>
      <el-tab-pane label="小程序详情" name="wechatMedia">
        <!-- 微信小程序详情 -->
        <div v-show="activeTab === 'wechatMedia'" class="p-6">
          <el-alert :closable="false">
            <ol>
              <li>微信小程序详情仅支持图片。</li>
            </ol>
          </el-alert>
          <div class="mb-6">
            <div
              class="font-bold mb-2"
              style="margin-bottom: 10px; margin-top: 10px"
            >
              小程序详情：
            </div>
            <el-upload
              :headers="uploadHeaders"
              :action="uploadUrl"
              list-type="picture-card"
              :limit="10"
              :on-success="(response) => handleUploadSuccess(response, 'desc')"
              :on-error="handleUploadError"
              :before-upload="beforeUpload"
              :on-remove="(file) => handleRemove(file, 'desc')"
              :on-preview="handlePictureCardPreview"
              :file-list="
                basicForm.desc.map((url, index) => ({
                  url,
                  name: `商品图片${index + 1}`,
                  uid: index,
                }))
              "
            >
              <el-icon><Plus /></el-icon>
            </el-upload>

            <!-- 添加图片预览对话框 -->
            <el-dialog v-model="dialogVisible" title="预览">
              <img
                w-full
                :src="dialogImageUrl"
                alt="Preview Image"
                style="max-width: 100%"
              />
            </el-dialog>
          </div>
        </div>
      </el-tab-pane>

      <!-- <el-tab-pane label="参数" name="params"> </el-tab-pane> -->
      <!-- <el-tab-pane label="SEO设置" name="seo"> </el-tab-pane> -->
      <!-- <el-tab-pane label="运费设置" name="freight"> </el-tab-pane> -->
      <!-- <el-tab-pane label="物流设置" name="logistics"> </el-tab-pane> -->
      <!-- <el-tab-pane label="促销设置" name="promotions"> </el-tab-pane> -->
    </el-tabs>
    <!-- 底部按钮 -->
    <div
      style="
        text-align: center;
        margin-top: 20px;
        padding-top: 20px;
        border-top: 1px solid #ebeef5;
      "
    >
      <el-button type="primary" @click="submitForm">确认提交</el-button>
      <el-button @click="goBack()">返回</el-button>
    </div>
  </el-card>
</template>

<script setup>
import { ref, shallowRef, onMounted, nextTick, computed, watch } from "vue"; // 添加 computed
import { useRoute, useRouter } from "vue-router";
import { Plus, RefreshRight } from "@element-plus/icons-vue";
import "@wangeditor/editor/dist/css/style.css";
import { Editor, Toolbar } from "@wangeditor/editor-for-vue";
import { generateGoodsCode } from "@/utils/public.js";
import { ElMessage } from "element-plus";
import { getCategories } from "@/api/category";
import { formatTreeData } from "@/utils/public.js";
import { getGoodDetail, updateGood, createGood } from "@/api/good";
import { usePageCurrentCategoryStore } from "@/stores/pageStore";
import { getBrands } from "@/api/brand";
import { nanoid } from "nanoid";

const currentCategory = usePageCurrentCategoryStore();

// 2. 路由相关
const route = useRoute();
const router = useRouter();
const spuId = route.query.id; // 获取由参数中的商品ID

// 判断是新建还是更新
const isNew = computed(() => !spuId);

// 3. 页面状态管理
// 当前活的标签页
const activeTab = ref("basic");
// 分类树数据
const categoryTree = ref([]);
const treeSelectRef = ref(null);

// 4. 表单相关
// 基础信息表单引用
const basicFormRef = ref(null);
// 基础信息表单数据
const basicForm = ref({
  // 系统相关
  saasId: 0, // SaaS平台ID
  storeId: 0, // 店铺ID

  // 基础信息
  title: "", // 商品标题/名称
  spuNo: "", // 商品编码(SPU编号)
  cateId: "", // 商品分类ID
  brandId: "", // 品牌ID
  brief: "", // 商品简介/简短描述

  // 媒体信息
  primaryImage: "", // 商品主图/封面图片
  images: [], // 商品图片列表/图集
  video: "", // 商品视频链接
  desc: [], // 小程序端商品详情图片列表

  // 商品属性
  productsDistributionType: 0, // 配送方式(0:无需配送 1:需要配送)
  isNomalVirtual: false, // 是否为虚拟商品
  status: 1, // 商品状态(1:上架 0:下架)
  unit: "", // 商品单位(个/件/套等)
  description: "", // 商品详细描述(富文本)

  // 规格相关
  skuIds: "", // SKU ID列表
  spesDesc: "", // 规格描述
  parameters: "", // 商品参数
  paramsIds: "", // 参数ID列表
  specs: [], // 规格列表
  specValues: [], // 规格值列表
  goodSpecValues: [], // 商品规格值关联
  openSpec: 0, // 是否启用多规格(0:否 1:是)
  newSpec: "", // 新规格临时存储

  // 销售相关
  spuStockQuantity: 0, // SPU总库存
  soldQuantity: 0, // 已售数量
  salePrice: 0, // 销售价
  linePrice: 0, // 划线价

  // 营销属性
  isRecommend: false, // 是否推荐商品
  isHot: false, // 是否热门商品
  spuTagList: "", // 商品标签列表
  labelIds: "", // 标签ID列表

  // 统计数据
  commentsCount: 0, // 评论数量
  viewCount: 0, // 查看次数

  // 时间相关
  uptime: null, // 上架时间
  downtime: null, // 下架时间
  createTime: null, // 创建时间
  updateTime: null, // 更新时间

  // 其他
  sort: 0, // 排序权重
  isDeleted: false, // 是否已删除
});

// 表单验证规则
const basicRules = {
  name: [
    { required: true, message: "请输入商品名称", trigger: "blur" },
    { max: 200, message: "商品名称不能超过200个字符", trigger: "blur" },
  ],
  cateId: [
    { required: true, message: "请选择商品分类", trigger: "change" },
    {
      type: "number",
      transform: (value) => Number(value),
      message: "分类ID必须是数字",
      trigger: "change",
    },
  ],
  spuNo: [
    { required: true, message: "请输入商品编", trigger: "blur" },
    { max: 50, message: "商品编码不能超过50个字符", trigger: "blur" },
  ],
  brief: [{ required: true, message: "请输入商品简介", trigger: "blur" }],
  unit: [{ required: true, message: "请选择商品单位", trigger: "change" }],
};

// SKU表单数据
const skuForm = ref({
  priceType: "global", // 价格类型主/单独设置
  enabled: false, // 是否启用SKU
  list: [
    {
      skuId: 0, // SKU ID
      spuId: 0, // 商品ID
      code: "", // SKU编码
      specValues: "", // SKU规格值
      image: "", // SKU图片
      salePrice: 100, // 售价
      linePrice: 150, // 划线价
      costPrice: 80, // 成本价
      marketPrice: 120, // 市场价
      stock: 10, // 库存
      weight: 500, // 重量
      points: 10, // 积分
    },
  ],
});

// 5. 富文本编辑器相关
const editorRef = shallowRef();
const toolbarConfig = {};
const editorConfig = { placeholder: "请输入内容..." };
const editorContent = ref("");

// 6. 上传相关配置
const uploadUrl = `${
  import.meta.env.VITE_UPLOADS_URL
}/api/FileUploadManage/upload`;
const uploadHeaders = {
  Authorization: `Bearer ${localStorage.getItem("token") || ""}`,
};

// 7. 方法定义
/**
 * 初始化获取分类列表
 */
const initGetCategory = async () => {
  try {
    const res = await getCategories();

    if (res.data && res.data.data) {
      categoryTree.value = formatTreeData(res.data.data, "id", "parentId");
    } else {
      categoryTree.value = [];
    }
  } catch (error) {
    console.error("获取分类列表失败:", error);
    ElMessage.error("获取分类列表失");
    categoryTree.value = [];
  }
};

// 分类树形结构默认配置
const defaultProps = {
  children: "children",
  label: "name",
  value: "id",
};

/**
 * 加载商品详情数据
 */
const loadGoodDetail = async () => {
  try {
    const res = await getGoodDetail(spuId);
    if (res.data && res.data.data) {
      const goodData = res.data.data;
      
      // 设置基础表单数据
      basicForm.value = {
        ...basicForm.value,
        name: goodData.title,
        spuNo: goodData.spuNo,
        cateId: goodData.cateId,
        brandId: goodData.brandId,
        brief: goodData.brief,
        primaryImage: goodData.primaryImage,
        images: goodData.images ? JSON.parse(goodData.images) : [],
        video: goodData.video,
        isVirtual: goodData.isNomalVirtual,
        isOnSale: goodData.status === 1,
        unit: goodData.unit,
        desc: goodData.desc ? JSON.parse(goodData.desc) : [],
        isRecommend: goodData.isRecommend,
        isHot: goodData.isHot,
        initialSales: goodData.soldQuantity,
        salePrice: goodData.salePrice || 0,
        linePrice: goodData.linePrice || 0,
        spuStockQuantity: goodData.spuStockQuantity || 0
      };

      // 设置富文本编辑器内容
      editorContent.value = goodData.description || "";

      // 处理规格数据
      if (goodData.specs && goodData.specValues) {
        specTreeData.value = goodData.specs.map((spec) => ({
          id: spec.specId,
          name: spec.specName,
          type: "spec",
          children: goodData.specValues
            .filter((value) => value.specId === spec.specId)
            .map((value) => ({
              id: value.valueId,
              name: value.valueName,
              type: "value",
              parentId: spec.specId,
            })),
        }));
      }

      // 设置SKU表单数据
      if (goodData.skus && goodData.skus.length > 0) {
        skuForm.value.enabled = goodData.openSpec === 1;
        skuForm.value.list = goodData.skus.map((sku) => {
          const specs = {};
          try {
            if (typeof sku.specValues === "string") {
              sku.specValues.split(";").forEach((pair) => {
                if (pair) {
                  const [specName, valueName] = pair.split(":");
                  if (specName && valueName) {
                    specs[specName] = valueName;
                  }
                }
              });
            }
          } catch (error) {
            console.error("解析规格值失败:", error);
          }

          return {
            skuId: sku.skuId || 0,
            spuId: sku.spuId || 0,
            code: sku.code || "",
            specValues: sku.specValues || "",
            image: sku.image || "",
            salePrice: sku.salePrice || 0,
            linePrice: sku.linePrice || 0,
            costPrice: sku.costPrice || 0,
            marketPrice: sku.marketPrice || 0,
            stock: sku.stock || 0,
            weight: sku.weight || 0,
            points: sku.points || 0,
            specs
          };
        });
        
        // 只在启用SKU时才更新总库存
        if (skuForm.value.enabled) {
          updateTotalStock();
        }
      }

      // 保证在一个 tick 中设置分类选中状态
      nextTick(() => {
        setCategorySelection(goodData.cateId);
      });
    }
  } catch (error) {
    console.error("获取商品详情失败:", error);
    ElMessage.error("获取商品详情失败");
  }
};

/**
 * 设置分类选择
 */
const setCategorySelection = (cateId) => {
  try {
    if (treeSelectRef.value && cateId) {
      // 使用 cateId 设置选中值
      basicForm.value.cateId = cateId;
      // 手动触发一次分类变更
      handleCategoryChange(cateId);
    }
  } catch (error) {
    console.error("设置分类选择失败:", error);
    ElMessage.error("设置分类失败");
  }
};

// 添加一个验证函数
const validateFormData = (data) => {
  // 检查必要的字符串字段
  if (typeof data.images !== "string" || typeof data.desc !== "string") {
    throw new Error("images 和 desc 必须是JSON字符串格式");
  }

  // 检查SKU数据
  if (data.skus && data.skus.length > 0) {
    data.skus.forEach((sku, index) => {
      if (typeof sku.specValues !== "string") {
        throw new Error(`第 ${index + 1} 个SKU的specValues必须是字符串格式`);
      }
    });
  }

  return true;
};

/**
 * 提交表单，更新或创建商品信息
 */
const submitForm = async () => {
  if (!basicFormRef.value) return;

  try {
    await basicFormRef.value.validate();

    // 构建基础数据
    const formData = {
      spuId: spuId ? Number(spuId) : 0,
      spuNo: basicForm.value.spuNo || "",
      saasId: 0,
      storeId: 0,
      cateId: Number(basicForm.value.cateId) || 0,
      brandId: Number(basicForm.value.brandId) || 0,
      title: basicForm.value.name || "",
      brief: basicForm.value.brief || "",
      primaryImage: basicForm.value.primaryImage || "",
      images: JSON.stringify(basicForm.value.images || []),
      video: basicForm.value.video || "",
      productsDistributionType: 0,
      skuIds: "",
      spesDesc: "",
      parameters: "",
      paramsIds: "",
      isNomalVirtual: basicForm.value.isVirtual || false,
      status: basicForm.value.isOnSale ? 1 : 0,
      unit: basicForm.value.unit || "",
      description: editorContent.value || "",
      desc: JSON.stringify(basicForm.value.desc || []),
      spuTagList: "",
      commentsCount: 0,
      viewCount: 0,
      spuStockQuantity: basicForm.value.spuStockQuantity || 0,
      soldQuantity: basicForm.value.initialSales || 0,
      uptime: null,
      downtime: null,
      sort: 0,
      labelIds: "",
      newSpec: "",
      openSpec: skuForm.value.enabled ? 1 : 0,
      isRecommend: basicForm.value.isRecommend || false,
      isHot: basicForm.value.isHot || false,
      salePrice: basicForm.value.salePrice || 0,
      linePrice: basicForm.value.linePrice || 0,
      isDeleted: false,

      // 处理规格数据
      specs: specTreeData.value.map((spec) => ({
        specId: spec.id,
        specName: spec.name || "",
        spuId: spuId ? Number(spuId) : 0,
      })),

      // 处理规格值数据
      specValues: specTreeData.value.flatMap((spec) =>
        (spec.children || []).map((value) => ({
          valueId: value.id,
          specId: spec.id,
          valueName: value.name || "",
          spuId: spuId ? Number(spuId) : 0,
        }))
      ),

      // 处理SKU数据
      skus: skuForm.value.enabled
        ? skuForm.value.list.map((sku) => {
            const specValuesString = Object.entries(sku.specs || {})
              .map(([specName, valueName]) => `${specName}:${valueName}`)
              .join(";");

            return {
              skuId: Number(sku.skuId) || 0,
              spuId: spuId ? Number(spuId) : 0,
              code: sku.code || "",
              specValues: specValuesString,
              image: sku.image || "",
              salePrice: Number(sku.salePrice) || 0,
              linePrice: Number(sku.linePrice) || 0,
              costPrice: Number(sku.costPrice) || 0,
              marketPrice: Number(sku.marketPrice) || 0,
              stock: Number(sku.stock) || 0,
              weight: Number(sku.weight) || 0,
              points: Number(sku.points) || 0,
            };
          })
        : [],
    };

    // 在提交前打印检查数据
    console.log("提交的数据:", JSON.stringify(formData, null, 2));

    try {
      // 验证数据格式
      validateFormData(formData);

      if (isNew.value) {
        await createGood(formData);
        ElMessage.success("创建成功");
      } else {
        await updateGood(formData.spuId, formData);
        ElMessage.success("修改成功");
      }

      router.push({
        path: "/goods/list",
      });
    } catch (validationError) {
      console.error("数据格式验证失败:", validationError);
      ElMessage.error(validationError.message);
      return;
    }
  } catch (error) {
    console.error(isNew.value ? "创建失败：" : "修改失败：", error);
    console.error("错误响应数据:", error.response?.data);
    if (error.response?.data?.errors) {
      const firstError = Object.values(error.response.data.errors)[0];
      ElMessage.error(Array.isArray(firstError) ? firstError[0] : firstError);
    } else {
      ElMessage.error(
        error.response?.data?.message ||
          error.message ||
          (isNew.value ? "创建失败" : "修改失败")
      );
    }
  }
};

/**
 * 生成商品码
 */
const generateCode = () => {
  basicForm.value.spuNo = generateGoodsCode();
};

/**
 * 返回列表页
 */
const goBack = () => {
  router.push({
    path: "/goods/list",
  });
};

/**
 * 重置表单（实际是回）
 */
const resetForm = () => {
  basicFormRef.value.resetFields();
};

/**
 * 富文本编辑器创建完成回调
 */
const handleCreated = (editor) => {
  editorRef.value = editor;
};

/**
 * 上传前校验
 */
const beforeUpload = (rawFile) => {
  const isJPG = rawFile.type === "image/jpeg";
  const isPNG = rawFile.type === "image/png";
  const isLt2M = rawFile.size / 1024 / 1024 < 2;

  if (!isJPG && !isPNG) {
    ElMessage.error("图片必须是JPG或PNG格式!");
    return false;
  }
  if (!isLt2M) {
    ElMessage.error("片大小不能超过2MB!");
    return false;
  }
  return true;
};

/**
 * 上传成功处理
 */
const handleUploadSuccess = (response, uploadType = "image") => {
  if (response.result) {
    const fullPath = `${import.meta.env.VITE_UPLOADS_URL}${response.filePath}`;

    switch (uploadType) {
      case "cover":
        basicForm.value.primaryImage = fullPath;
        break;
      case "gallery":
        basicForm.value.images.push(fullPath);
        break;
      case "desc":
        basicForm.value.desc.push(fullPath);
        break;
      case "video":
        basicForm.value.video = fullPath;
        break;
      case "sku":
        // TODO: 处理SKU图片上传
        break;
    }

    ElMessage.success(response.message || "上传成功");
  } else {
    ElMessage.error("上传失败: " + (response.message || "未知错误"));
  }
};

/**
 * 上传失败处理
 */
const handleUploadError = (err) => {
  ElMessage.error("上传失败: " + err);
};

/**
 * 删除图片的处理函数
 */
const handleRemove = (file, type = "images") => {
  const array =
    type === "images" ? basicForm.value.images : basicForm.value.desc;
  const index = array.findIndex((url) => url === file.url);
  if (index > -1) {
    array.splice(index, 1);
  }
};

/**
 * 图片预览处理函数
 */
const handlePictureCardPreview = (file) => {
  dialogImageUrl.value = file.url;
  dialogVisible.value = true;
};

// 8. 生命周期钩子
onMounted(async () => {
  try {
    // 加载品牌列表和分类树
    await Promise.all([initGetCategory(), initBrands()]);

    // 再加载商品详情
    if (!isNew.value) {
      await loadGoodDetail();
    }
  } catch (error) {
    console.error("初始化失败:", error);
    ElMessage.error("加载数据失败");
  }
});

// 修改分类选择的处理函数
const handleCategoryChange = (value) => {
  basicForm.value.cateId = value;
};

// 在 script setup 中加单位选项
// 添加在其他 const 定义的地方
const unitOptions = [
  "盒",
  "提",
  "盆",
  "件",
  "套",
  "支",
  "包",
  "个",
  "双",
  "扎",
  "块",
  "瓶",
  "罐",
];

// 添加品牌选项的响应式数据
const brandOptions = ref([]);

// 修改获取品牌列表的方法
const initBrands = async () => {
  try {
    const res = await getBrands();
    if (res.data) {
      brandOptions.value = res.data;
    }
  } catch (error) {
    console.error("获取品牌列表失败:", error);
    ElMessage.error("获取品牌列表失败");
  }
};

// 在其他 ref 定义的地方添加
const dialogVisible = ref(false);
const dialogImageUrl = ref("");

const specTreeData = ref([]); // 规格树数据

// 生成SKU组合的函数
const generateSkus = () => {
  if (!specTreeData.value || specTreeData.value.length === 0) {
    skuForm.value.enabled = false;
    skuForm.value.list = [];
    return;
  }

  const validSpecs = specTreeData.value.filter(
    (spec) => spec.name && spec.children && spec.children.length > 0
  );

  if (validSpecs.length === 0) {
    skuForm.value.enabled = false;
    skuForm.value.list = [];
    return;
  }

  // 生成笛卡尔积
  const generateCombinations = (specs) => {
    if (specs.length === 0) return [{}];

    const [currentSpec, ...restSpecs] = specs;
    const restCombinations = generateCombinations(restSpecs);

    return currentSpec.children.flatMap((value) =>
      restCombinations.map((combination) => ({
        ...combination,
        [currentSpec.name]: value.name,
      }))
    );
  };

  const combinations = generateCombinations(validSpecs);

  // 更新 SKU 列表
  skuForm.value.list = combinations.map((combo) => {
    const specValuesString = Object.entries(combo)
      .map(([specName, valueName]) => `${specName}:${valueName}`)
      .join(";") + ";";

    return {
      skuId: 0,
      spuId: spuId ? Number(spuId) : 0,
      code: generateGoodsCode(),
      specValues: specValuesString,
      image: "",
      salePrice: 100,
      linePrice: 150,
      costPrice: 80,
      marketPrice: 120,
      stock: 10,
      weight: 500,
      points: 10,
      specs: combo,
    };
  });

  skuForm.value.enabled = true;
  
  // 生成 SKU 后立即更新总库存
  updateTotalStock();
};

// 修改删除节点的方法
const removeNode = (node, data) => {
  try {
    const parent = node.parent;
    if (!parent) return;

    const children = parent.data.children || parent.data;
    const index = children.findIndex((d) => d.id === data.id);
    if (index > -1) {
      children.splice(index, 1);
      // 只有在确实删除了节点才重新生成SKU
      generateSkus();
    }
  } catch (error) {
    console.error("删除节点失败:", error);
    ElMessage.error("删除节点失败");
  }
};

// 修改输入框失焦事件处理
const handleInputBlur = (data) => {
  try {
    if (data.inputValue && data.inputValue.trim()) {
      data.name = data.inputValue.trim();
      data.isEditing = false;
      data.inputValue = "";
      // 只有在成功更新名称后才重新生成SKU
      generateSkus();
    } else {
      ElMessage.warning("名称不能为空");
      // 如果名称为空，保持编辑状态
      data.isEditing = true;
    }
  } catch (error) {
    console.error("处理输入框失焦事件失败:", error);
    ElMessage.error("更新失败");
  }
};

// 添加规格的方法也需要修改
const addSpec = () => {
  try {
    const newSpec = {
      id: `spec_${nanoid()}`,
      name: "新规格",
      type: "spec",
      isEditing: true,
      inputValue: "",
      children: [],
    };
    specTreeData.value.push(newSpec);
  } catch (error) {
    console.error("添加规格失败:", error);
    ElMessage.error("添加规格失败");
  }
};

// 添加规格值的方法也需要修改
const addSpecValue = (specData) => {
  try {
    const newValue = {
      id: `value_${nanoid()}`,
      name: "新规格值",
      type: "value",
      isEditing: true,
      inputValue: "",
      parentId: specData.id,
    };
    if (!specData.children) {
      specData.children = [];
    }
    specData.children.push(newValue);
  } catch (error) {
    console.error("添加规格值失败:", error);
    ElMessage.error("添加规格值失败");
  }
};

// 修改处理总库存变更的方法
const handleTotalStockChange = (value) => {
  if (!skuForm.value.enabled) {
    basicForm.value.spuStockQuantity = value;
  }
};

// 修改更新总库存的方法
const updateTotalStock = () => {
  // 只在启用了SKU时才计算总库存
  if (skuForm.value.enabled) {
    const total = skuForm.value.list.reduce(
      (sum, sku) => sum + (Number(sku.stock) || 0),
      0
    );
    basicForm.value.spuStockQuantity = total;
  }
  // 未启用SKU时，不修改总库存值
};

// 修改处理SKU启用状态变更的方法
const handleSkuEnabledChange = (enabled) => {
  skuForm.value.enabled = enabled;
  if (enabled) {
    // 启用SKU时，如果有SKU列表则重新计算总库存
    if (skuForm.value.list.length > 0) {
      updateTotalStock();
    }
  }
};

// 监听单个SKU的库存变化
const handleSkuStockChange = (newStock, sku) => {
  sku.stock = Number(newStock) || 0;
  // 立即更新总库存
  updateTotalStock();
};
</script>

<style scoped>
.content-wrapper {
  min-height: 500px;
}

.product-form :deep(.el-tabs__nav-wrap::after) {
  height: 1px;
}

.product-form :deep(.el-input-number .el-input__wrapper) {
  width: 160px;
}

/* 移除之前的 flex 相关样式 */
:deep(.el-card__body) {
  padding: 20px;
}

.el-form-item {
  margin-bottom: 22px;
}

:deep(.el-input__wrapper),
:deep(.el-textarea__inner) {
  box-shadow: 0 0 0 1px #dcdfe6 inset;
}

:deep(.el-input__wrapper:hover),
:deep(.el-textarea__inner:hover) {
  box-shadow: 0 0 0 1px #c0c4cc inset;
}

:deep(.el-input__wrapper.is-focus),
:deep(.el-textarea__inner:focus) {
  box-shadow: 0 0 0 1px #409eff inset;
}

/* 按钮样式化 */
:deep(.el-button) {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  gap: 4px;
}

/* 输入框统一宽度 */
:deep(.el-select),
:deep(.el-input-number) {
  width: 360px;
}

/* 调整表单项间距 */
.other-params {
  border-top: 1px solid #ebeef5;
  padding-top: 20px;
  margin-top: 30px;
}

.other-params .el-form-item:first-child {
  margin-top: 20px;
}

/* 调整两列布局的样式 */
.other-params :deep(.el-form-item) {
  margin-bottom: 30px;
}

/* 确保输入框和选择器宽度一致 */
.other-params :deep(.el-select),
.other-params :deep(.el-input-number) {
  width: 240px !important;
}

/* 调整开关的对齐方式 */
.other-params :deep(.el-switch) {
  margin-top: 8px;
}

/* 调整提示文字的样式 */
.other-params .text-gray-400 {
  margin-top: 4px;
  font-size: 12px;
  line-height: 1.4;
}

/* 添加 label 背景色样式 */
:deep(.el-form-item__label) {
  background-color: #f5f7fa;
  padding: 0 12px;
  height: 32px;
  line-height: 32px;
  border-radius: 4px;
  margin-right: 12px;
  color: #606266;
}

/* 调整 label 后内容的对齐 */
:deep(.el-form-item__content) {
  margin-left: 0 !important;
}

/* 确保表单项布局正确 */
:deep(.el-form-item) {
  display: flex;
  align-items: flex-start;
}

/* 调整文本域类型表单项的对齐 */
:deep(.el-form-item--default .el-form-item__label) {
  margin-top: 5px;
}

/* 确保开关类型的表单项对齐 */
:deep(.el-switch) {
  margin-top: 5px;
}

/* 输入框和按钮组合样式 */
.input-with-button {
  display: inline-flex;
  align-items: center;
}

.input-with-button .generate-btn {
  margin-left: 8px;
  height: 32px;
  padding: 0 16px;
}

/* 确保输入框高度一致 */
:deep(.el-input__wrapper) {
  height: 32px;
  line-height: 32px;
}

/* 按钮内部图标和文字对齐 */
.generate-btn {
  display: inline-flex;
  align-items: center;
  gap: 4px;
}

/* 移除之前可能影响对齐的样式 */
.flex.items-center.gap-2 {
  display: inline-flex;
}

/* 商品分类选择器样式 */
.category-select {
  display: inline-flex;
  align-items: center;
}

.category-select .add-category-btn {
  margin-left: 16px; /* 增加间距 */
  height: 32px;
  padding: 0 16px;
}

/* 添加封面图上传的样式 */
.avatar-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 178px;
  height: 178px;
}

.avatar-uploader:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
  display: flex;
  justify-content: center;
  align-items: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
  object-fit: cover;
}

/* 在 <style scoped> 中修改或添加以下样式 */

/* 基表单项样式 */
:deep(.el-form-item) {
  display: flex !important;
  margin-bottom: 22px;
}

/* 表单项标签样式 */
:deep(.el-form-item__label) {
  background-color: #f5f7fa;
  padding: 0 12px;
  height: 32px;
  line-height: 32px;
  border-radius: 4px;
  margin-right: 12px;
  color: #606266;
  flex-shrink: 0; /* 防止标签缩小 */
  display: flex;
  align-items: center;
}

/* 表单项内容区域样式 */
:deep(.el-form-item__content) {
  display: flex;
  align-items: center;
  flex: 1;
  margin-left: 0 !important;
}

/* 其他参数部分的特殊样式 */
.other-params :deep(.el-form-item) {
  margin-bottom: 20px;
}

/* 调整开关组件的对齐 */
.other-params :deep(.el-switch) {
  margin-top: 0;
  height: 32px;
  display: flex;
  align-items: center;
}

/* 调整输入框和选择器的宽度 */
.other-params :deep(.el-select),
.other-params :deep(.el-input-number) {
  width: 240px !important;
}

/* 调整文本域类型的表单项 */
:deep(.el-form-item--textarea) .el-form-item__label {
  align-items: flex-start;
  padding-top: 5px;
}

/* 确保所有输入框组件高度一致 */
:deep(.el-input__wrapper),
:deep(.el-select__wrapper) {
  height: 32px !important;
}

/* 移除可能影响对齐的其他样式 */
.other-params :deep(.el-form-item__content) {
  flex-wrap: nowrap;
}

/* 标签页样式 */
:deep(.el-tabs__nav-wrap) {
  padding: 0 20px;
  background-color: #f5f7fa;
}

:deep(.el-tabs__item) {
  height: 40px;
  line-height: 40px;
  padding: 0 20px;
  transition: all 0.3s;
}

/* 未选中标签的样式 */
:deep(.el-tabs__item:not(.is-active)) {
  color: #606266;
}

/* 选中标签的样式 */
:deep(.el-tabs__item.is-active) {
  color: #409eff;
  background-color: #fff;
  border-radius: 4px 4px 0 0;
  /* 添加底部边框遮挡底线 */
  border-bottom: 2px solid #fff;
  margin-bottom: -2px;
}

/* 标签页下方的线条 */
:deep(.el-tabs__nav-wrap::after) {
  height: 1px;
  background-color: #dcdfe6;
}

/* 标悬停效果 */
:deep(.el-tabs__item:hover) {
  color: #409eff;
}

/* 标签内容区域样式 */
:deep(.el-tabs__content) {
  padding: 20px;
  background-color: #fff;
}

.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding: 4px 0;
  max-width: 400px; /* 限制整体最大宽度 */
}

.name-wrapper {
  flex: 0 0 180px; /* 固定宽度为180px */
  min-width: 0; /* 允许内容收缩 */
}

.name-text {
  display: inline-block;
  max-width: 180px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.operation-buttons {
  flex: 0 0 auto;
  display: flex;
  gap: 8px;
  margin-left: 12px;
}

/* 调整树节点样式 */
.spec-tree :deep(.el-tree-node__content) {
  height: 40px; /* 减小高度 */
  padding: 0 12px;
  margin: 2px 0;
  border-radius: 4px;
  background: white;
}

/* 调整规格值的缩进和样式 */
.spec-tree :deep(.el-tree-node.is-expanded > .el-tree-node__children) {
  padding-left: 24px; /* 减小进 */
  margin: 4px 0;
}

/* 输入框样式优 */
.spec-tree :deep(.el-input__wrapper) {
  margin: 0 4px;
}

/* 调整按钮样式使其更紧凑 */
.spec-tree :deep(.el-button--small) {
  padding: 4px 8px;
}

/* 确保树的整体宽度合适 */
.spec-tree {
  max-width: 460px; /* 适当限制整体宽度 */
  padding: 16px;
  background: #f8f9fa;
  border-radius: 8px;
}

/* 调整两列布局的间距 */
.el-row {
  margin-bottom: 20px;
}

/* 确保输入框和数字输入框宽度一致 */
:deep(.el-input-number.is-controls-right .el-input__wrapper) {
  width: 260px !important;
}

/* 调整带按钮的输入框组合 */
.input-with-button {
  display: flex;
  align-items: center;
  gap: 8px;
}

.input-with-button .el-button {
  flex-shrink: 0;
}

/* 调整嵌套行的样式 */
.el-row .el-row {
  margin-bottom: 0;
}

/* 调整嵌套列中的表单项样式 */
.el-col .el-row .el-form-item {
  margin-bottom: 0;
}

/* 调整数字输入框的宽度 */
:deep(.el-input-number.is-controls-right .el-input__wrapper) {
  width: 120px !important;
}

/* 当在嵌套行中时，调整数字输入框的宽度 */
.el-row .el-row :deep(.el-input-number.is-controls-right .el-input__wrapper) {
  width: 120px !important;
}

/* 添加总库存和已售数的样式 */
.stock-summary {
  background-color: #f8f9fa;
  padding: 16px;
  border-radius: 8px;
  margin: 16px 0;
}

.stock-summary .el-form-item {
  margin-bottom: 0;
}

.stock-summary :deep(.el-input-number.is-disabled .el-input__wrapper) {
  background-color: #f5f7fa;
}
</style>
